/**
 * 多久以前
 * @param timestamp  时间戳
 */
function getFrom(timestamp: number | string | Date = new Date().getTime()) {
    if (typeof timestamp == 'string') {
        timestamp = new Date(timestamp).getTime();
    }

    // 补全为13位
    const arrTimestamp: Array<string> = (timestamp + '').split('');
    for (let start = 0; start < 13; start++) {
        if (!arrTimestamp[start]) {
            arrTimestamp[start] = '0';
        }
    }
    timestamp = Number(arrTimestamp.join('')) * 1;

    const minute = 1000 * 60;
    const hour = minute * 60;
    const day = hour * 24;
    const halfamonth = day * 15;
    const month = day * 30;
    const now = new Date().getTime();
    const diffValue = now - timestamp;

    // 如果本地时间反而小于变量时间
    if (diffValue < 0) {
        return '不久前';
    }
    // 计算差异时间的量级
    const monthC = diffValue / month;
    const weekC = diffValue / (7 * day);
    const dayC = diffValue / day;
    const hourC = diffValue / hour;
    const minC = diffValue / minute;

    // 数值补0方法
    const zero = function (value: number) {
        if (value < 10) {
            return '0' + value;
        }
        return value;
    };

    // 使用
    if (monthC > 12) {
        // 超过1年，直接显示年月日
        return (function () {
            const date = new Date(timestamp);
            return date.getFullYear() + '年' + zero(date.getMonth() + 1) + '月' + zero(date.getDate()) + '日';
        })();
    } else if (monthC >= 1) {
        return parseInt(monthC + '') + '月前';
    } else if (weekC >= 1) {
        return parseInt(weekC + '') + '周前';
    } else if (dayC >= 1) {
        return parseInt(dayC + '') + '天前';
    } else if (hourC >= 1) {
        return parseInt(hourC + '') + '小时前';
    } else if (minC >= 1) {
        return parseInt(minC + '') + '分钟前';
    }
    return '刚刚';
}

/**
 * 剩余时间格式化
 * @param {Number} t - 剩余多少秒
 * @return {Object}  format - 格式后的天时分秒对象
 */
function getMuch(t: number) {
    const format: any = {
        d: '00',
        h: '00',
        m: '00',
        s: '00',
    };
    if (t > 0) {
        const d = Math.floor(t / 86400);
        const h = Math.floor((t / 3600) % 24);
        const m = Math.floor((t / 60) % 60);
        const s = Math.floor(t % 60);
        format.d = d < 10 ? '0' + d : d;
        format.h = h < 10 ? '0' + h : h;
        format.m = m < 10 ? '0' + m : m;
        format.s = s < 10 ? '0' + s : s;
    }
    return format;
}

export default {
    getFrom,
    getMuch,
};
